﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using TpBaseObjects.Objects;
using TpContracts;
using TpData.Manager;
using TpTools;
using myOffice = Microsoft.Office.Interop;

namespace TpTimerService {
    public partial class TpService : ServiceBase {

        #region Members

        private System.Timers.Timer timer;
        private const string errType = "Err";
        private const string logType = "Log";
        private const string logArea = "TpTimerService.TpService";
        private DateTime lastTime = new DateTime(2000, 1, 1);
        private TecUserObj myUser;
        private myOffice.Excel.Application exApp;

        #endregion

        #region Constructor

        public TpService() {
            InitializeComponent();
            //try {

            //} catch (Exception ex) {
            //    eventLog1.WriteEntry("TpTimerService.TpService: (ERR) " + ex.Message);
            //}

        }

        #endregion

        #region Methods

        private void CheckFiles(object sender, System.Timers.ElapsedEventArgs e) {
            //eventLog1.WriteEntry("CheckFiles");
            try {
                eventLog1.WriteEntry("CheckFiles");
                foreach (TimerFileObj tf in TimerFileDataManager.LoadTimerFilesByUser(myUser.UserID)) {
                    if (tf != null && tf.FileName != "") {
                        eventLog1.WriteEntry("CheckFiles: File: " + tf.FileName);
                        eventLog1.WriteEntry("CheckFiles: SetDate: " + tf.SetDate.ToString());
                        eventLog1.WriteEntry("CheckFiles: TimerCount: " + tf.TimerCount.ToString());
                        DateTime newDate = tf.SetDate.AddSeconds(Convert.ToDouble(tf.TimerCount));
                        eventLog1.WriteEntry("CheckFiles: newDate: " + newDate.ToString());

                        try {
                            eventLog1.WriteEntry("CheckFiles: Start Try");
                            if (DateTime.Now >= newDate) {
                                eventLog1.WriteEntry("CheckFiles: Close File: " + tf.FileName);
                                CloseExcelFile(tf.FileName);
                            }
                        } catch (Exception ex) {
                            eventLog1.WriteEntry("CheckFiles: Error : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                        }
                    }
                }
            } catch (Exception ex) {
                eventLog1.WriteEntry("TpTimerService.TpService.timer_Elapsed: (ERR) " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        private void CloseExcelFile(string fileName) {
            eventLog1.WriteEntry("CloseExcelFiles: " + fileName);
            try {
                if (exApp == null) {
                    eventLog1.WriteEntry("CloseExcelFiles: exApp is null 1");
                    exApp = this.GetExcelApplication();
                }
                if (exApp == null) {
                    eventLog1.WriteEntry("CloseExcelFiles: exApp is null 2");
                }
                if (exApp != null) {
                    foreach (myOffice.Excel.Workbook wb in exApp.Workbooks) {
                        eventLog1.WriteEntry("CloseExcelFiles: File: " + wb.Name);
                        if (wb.Name == fileName) {
                            try {
                                wb.Save();
                                wb.Close(SaveChanges: true);
                                TimerFileDataManager.RemoveTimerFileObj(fileName, myUser.UserID);
                                LogDataManager.SaveLog(myUser.UserID, logType, logArea, "File: " + fileName + " is closed & saved", false);
                            } catch (Exception ex) {
                                LogDataManager.SaveLog(myUser.UserID, errType, logArea, "CloseExcelFile: " + ex.Message, false);
                                Office.SendEmail(myUser.EMail, "Error (" + wb.Name + ")", "Fehler beim Schließen der Datei " + wb.Name);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                eventLog1.WriteEntry("CloseExcelFiles: " + ex.Message);
            }
        }

        private Microsoft.Office.Interop.Excel.Application GetExcelApplication() {
            try {
                eventLog1.WriteEntry("GetExcelApplication: Start");
                Process[] procs = Process.GetProcesses();
                foreach (Process proc in procs) {
                    if (proc.ProcessName.IndexOf("EXCEL") > -1) {
                        eventLog1.WriteEntry("GetExcelApplication: Process is found");
                        return (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
                    }
                }
                return new Microsoft.Office.Interop.Excel.Application();
            } catch (Exception ex) {
                eventLog1.WriteEntry("GetExcelApplication: " + ex.Message);
            }
            return null;
        }

        protected override void OnContinue() {
            //eventLog1.WriteEntry("OnContinue");
            //if (lastTime.AddMinutes(1) <= DateTime.Now) {
            //    CheckFiles();
            //    lastTime = DateTime.Now;
            //}
        }

        protected override void OnStart(string[] args) {
            eventLog1.WriteEntry("In OnStart");

            try {
                this.timer = new System.Timers.Timer(60000D);  // 60000 milliseconds = 60 seconds
                this.timer.AutoReset = true;
                this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.CheckFiles);
                this.timer.Start();
                myUser = TecUserDataManager.LoadTecUser(Environment.UserName);
                LogDataManager.SaveLog(myUser.UserID, logType, logArea, "OnStart: OK", false);

            } catch (Exception ex) {
                eventLog1.WriteEntry("TpTimerService.TpService.OnStart: (ERR) " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        protected override void OnStop() {
            eventLog1.WriteEntry("In onStop.");
            try {
                LogDataManager.SaveLog(myUser.UserID, logType, logArea, "OnStop: OK", false);
            } catch (Exception ex) {
                eventLog1.WriteEntry("TpTimerService.TpService.OnStop: (ERR) " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        //private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
        //    eventLog1.WriteEntry("Timer Elapsed");
        //    try {
        //        foreach (TimerFileObj tf in TimerFileDataManager.LoadTimerFilesByUser(myUser.UserID)) {
        //            if (tf.SetDate.AddSeconds(Convert.ToDouble(tf.TimerCount)) <= DateTime.Now) {
        //                CloseExcelFile(tf.FileName);
        //            }
        //        }
        //    } catch (Exception ex) {
        //        eventLog1.WriteEntry("TpTimerService.TpService.timer_Elapsed: (ERR) " + ex.Message); 
        //    }
        //}

        #endregion

    }
}
